<?php
namespace app\api\model;
use plugin\filter;
use think\Db;
use think\Model;
use app\api;
use think\Session;

/*客服模型*/
class Kf extends CommonModel
{
    private $table_name = 'kf';
    public function __construct($args = [])
    {
        parent::__construct($args);
    }

    /**初始化参数
     * @param $args [client_id,token,enc_string,nickname]
     * @return array
     */
    private function default_param($args)
    {
        $default = [
            "client_id"     => "",
            "enc_client_id" => "",
            "nickname"      => "匿名",
            "kf_username"  => "",
            "kf_password"   => "",
        ];
        return array_merge($default,$args);
    }

    /**客服登录接口
     * @param $args [kf_username,kf_password]
     * @return bool
     */
    public function login($args)
    {
        //初始化参数
        $args = $this->default_param($args);

        if(empty($args['kf_username']) || empty($args['kf_password'])) return false;

        //查询客服信息
        $kf = $this->info(['kf_username'=>$args['kf_username']]);
        //检测密码
        if(empty($kf)
            || !$this->chkKfPassword(['db_password'=>$kf['kf_password'],'kf_password'=>$args['kf_password'],'kf_enc_string'=>$kf['kf_enc_string']])
        ) return false;

        $this->clear_session();

        //更新客服加密窜
        $kf['kf_password'] = $args['kf_password'];
        $this->updateKfEncString($kf);

        //更新token
        $userModel = new Users();
        $token = $userModel->resetEncString($kf);

        return [
            'client_id' => $kf['client_id'],
            'enc_client_id'=> $this->EncUserid($kf['client_id']),
            'user_name' => $kf['nickname'],
            'nickname'  => $kf['nickname'],
            'is_kf'     => 1,
            'token'     => $token
        ];

    }

    /**检测kf密码正确性
     * @param $args [db_password数据库字符串,kf_password用户输入的密码,kf_enc_string数据库加密字符串]
     * @return bool
     */
    public function chkKfPassword($args)
    {

        return $args['db_password'] == $this->generateKfPassword($args);
    }

    /**生成客服密码窜
     * @param $args [kf_password,kf_enc_string]
     * @return string
     */
    private function generateKfPassword($args)
    {
        return md5($args['kf_password'].$args['kf_enc_string']);
    }

    /**更新客服密码加密窜
     * @param $args [client_id,kf_password]
     */
    private function updateKfEncString($args)
    {
        $enc_string = randString(15);
        db($this->table_name)->where(['kf_id'=>$args['kf_id']])->update([
            'kf_enc_string'=>$enc_string,
            'kf_password'=>$this->generateKfPassword(['kf_password'=>$args['kf_password'],'kf_enc_string'=>$enc_string])
        ]);
    }


    /**新增一个客服
     * @param $args [kf_username,kf_password,nickname,]
     * @return client_id
     */
    public function addKf($args)
    {
        //初始化参数
        $args = $this->default_param($args);
        $enc_string= randString(15);
        //客服账号密码不得空
        if(empty($args['kf_username'])  || empty($args['kf_password']) || empty($args['nickname'])) return false;
        //如果客服已存在，则返回false
        if(!empty($this->info(['kf_username'=>$args['kf_username']]))) return false;
        //插入数据库
        $kf_id =  db($this->table_name)->insertGetId([
            'nickname'      => $args['nickname'],
            'kf_username'   => $args['kf_username'],
            'kf_password'   => $this->generateKfPassword(['kf_enc_string'=>$enc_string,'kf_password'=>$args['kf_password']]),
            'kf_enc_string' => $enc_string
        ]);

        //插入用户表
        return $this->addKfInUser(['kf_id'=>$kf_id]);
    }

    /**把客服id插入用户表中
     * @param $args ['kf_id'] kf_id值
     * @return client_id
     */
    public function addKfInUser($args)
    {
        $userModel = new Users();
        return $userModel->add_user(['kf_id'=>$args['kf_id']]);
    }

    /**获取用户名
     * @param array $args key:[client_id,kf_username,enc_client_id], 中括号表示任选一个可以查询
     * @return bool
     */
    public function info($args)
    {

        if(empty($args)) return false;
        //参数合并
        $args = $this->default_param($args);
        //如果没有查询信息，返回空
        if(empty($args['client_id'] ) && empty($args['kf_username']) && empty($args['enc_client_id'])) return false;

        //根据client_id,kf_username,enc_client_id其中一个查询查
        if(!empty($args['client_id']))
        {
            $filter = ['u.client_id'=>$args['client_id']];
        }
        elseif(!empty($args['kf_username']))
        {
            $filter = ['k.kf_username'=>$args['kf_username']];
        }
        elseif(!empty($args['enc_client_id']))
        {
            $filter = ['u.enc_client_id'=>$args['enc_client_id']];
        }
        if(empty($filter)) return false;

        //返回查询信息
        return  db($this->table_name)->alias('k')->field('k.*,u.client_secrect,u.enc_string,u.enc_client_id,u.client_id')->join('ecs_user u','u.kf_id = k.kf_id','LEFT')->where($filter)->find();
    }

    public function getAllKf($onLineArr = [])
    {
        //获取所有客服列表
        $kf_arr = db($this->table_name)->alias('k')
                    ->field('u.enc_client_id,k.nickname,k.motto,k.kf_id')
                    ->join('ecs_user u','u.kf_id = k.kf_id','LEFT')
                    ->select();
        //筛选所有客服是否在线
        return $this->setOnLineState($kf_arr,$onLineArr);
    }
}